<template lang="pug">
  kalix-dialog.user-add(title='教师分配' bizKey="createexam" ref="kalixBizDialog" v-bind:formModel.sync="formModel"
  v-bind:targetURL="targetURL" v-bind:submitCustom="submitCustom")
    div.el-form(slot="dialogFormSlot"
    style="max-height:550px;min-height:550px;overflow:auto;border: 1px solid #d0d0d0;margin:-30px 0 -20px")
      el-tree.filter-tree(v-bind:data="treeData" v-bind:props="defaultProps"
      node-key="id" highlight-current show-checkbox
      v-bind:default-checked-keys="checkedKeys" default-expand-all
      empty-text="数据加载中!" ref="baseTree"
      v-on:check-change="checkChange")
</template>

<script type="text/ecmascript-6">
  import FormModel from './examModel'
  import {ExamOrgTeacherURL, ExamOrgTeacherTreeURL} from '../config.toml'
  import {ON_REFRESH_DATA} from 'kalix-vue-lib/src/components/common/event.toml'

  export default {
    name: 'ExamTeacher',
    data() {
      return {
        formModel: Object.assign({}, FormModel),
        treeDataURL: ExamOrgTeacherTreeURL,
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        checkedKeys: [],
        ids: [],
        targetURL: ExamOrgTeacherURL,
        orgData: {}
      }
    },
    watch: {
      formModel: {
        handler: 'watchFormModel'
      }
    },
    methods: {
      // 获取数据
      getData() {
        this.treeData = []
        this.checkedKeys = []
        if (!this.treeDataURL) {
          return
        }
        if (!this.formModel.id) {
          return
        }
        // let url = this.treeDataURL + '/' + this.formModel.id + '/authorizations'
        let url = this.treeDataURL
        this.axios.request({
          method: 'GET',
          url: url,
          params: {
            examId: this.formModel.id
          }
        }).then(res => {
          if (res.data.treeData && res.data.treeData.children) {
            this.treeData = res.data.treeData.children
            // 获取选中节点, 并设置所有节点disable=true
            this.setCheckKeys(res.data.orgIds)
            // this.getCheckedKeys(this.treeData)
          }
        })
      },
      setCheckKeys(orgIds) {
        if (orgIds && orgIds.length) {
          for (let i = 0; i < orgIds.length; i++) {
            this.checkedKeys.push(orgIds[i])
          }
        }
      },

      close() {
        this.onCancelClick()
      },
      // 封装数据格式
      getLeafCheckedIds(array) {
        if (array && array.length > 0) {
          for (let i = 0; i < array.length; i++) {
            if (array[i].children) {
              if (array[i].children.length === 0) {
                if (array[i].checked) {
                  this.ids.push(array[i].id)
                }
              } else {
                this.getLeafCheckedIds(array[i].children)
              }
            }
          }
        }
      },
      watchFormModel(newVal) {
        console.log('getData', newVal)
        this.getData()
      },
      submitCustom(baseDialog) {
        this.getLeafCheckedIds(this.treeData)
        let orgIds = ''
        if (this.ids.length > 0) {
          for (let i = 0; i < this.ids.length; i++) {
            if (i > 0) {
              orgIds += ","
            }
            orgIds += this.ids[i]
          }
        }
        this.orgData = {
          examId: this.formModel.id,
          orgIds: orgIds
        }

        baseDialog.$refs.dialogForm.validate((valid) => {
          if (valid) {
            this.axios.request({
              method: baseDialog.isEdit ? 'PUT' : 'POST',
              url: baseDialog.isEdit ? `${this.targetURL}/${this.formModel.id}` : this.targetURL,
              data: this.orgData,
              params: {}
            }).then(response => {
              if (response.data.success) {
                this.$KalixMessage.success(response.data.msg)
                baseDialog.visible = false
                baseDialog.$refs.dialogForm.resetFields()
                baseDialog.submitComplete()
              } else {
                this.$KalixMessage.error(response.data.msg)
                baseDialog.submitComplete()
              }
              // 刷新列表
              this.$KalixEventBus.$emit(ON_REFRESH_DATA)
              baseDialog._afterDialogClose()
              console.log('[kalix] dialog submit button clicked !')
              baseDialog.visible = false
            })
          } else {
            this.$KalixMessage.error('请检查输入项！')
            baseDialog.submitComplete()
            return false
          }
        })

        this.ids = []
      },
      checkChange(a, b, c) {
        if (b) {
          a.checked = true
        } else if (c) {
          a.checked = true
        } else {
          a.checked = false
        }
      }
    }
  }
</script>

<style scoped>

</style>
